package com.chaos.meta.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
 
/**
 * @author naicha
 */
@Component
public class JedisCacheUtil {
 
	@Autowired
	private JedisPool jedisPool;

	/**
	 * Description:给某个key设值
	 */
	public void set(String key, String value) {
		Jedis client = jedisPool.getResource();
		try {
			client.set(key, value);
		} finally {
			returnJedis(client);
		}
	}

	/**
	 * Description:给某个key设值，设置过期时间expire，-1表示不过期，遵循redis的LRU算法。
	 */
	public void set(String key, String value, int expireSecond) {
		Jedis client = jedisPool.getResource();
		try {
			client.set(key, value);
			if(expireSecond != -1) {
				client.expire(key, expireSecond);
				//另一种设置方式:NX是不存在时才set,XX是存在时才set,EX是秒,PX是毫秒:client.set(key, value, "NX", "EX", expireSecond);
			}
		} finally {
			returnJedis(client);
		}
	}

	/**
	 * Description:根据key获取value
	 */
	public String get(String key) {
		Jedis client = jedisPool.getResource();
		try {
			return client.get(key);
		} finally {
			returnJedis(client);
		}
	}

	/**
	 * Description:判断key是否存在
	 */
	public boolean existKey(String key) {
		Jedis client = jedisPool.getResource();
		try {
			return client.exists(key);
		} finally {
			returnJedis(client);
		}
	}

	/**
	 * Description:根据key删除
	 */
	public void delKey(String key) {
		Jedis client = jedisPool.getResource();
		try {
			client.del(key);
		} finally {
			returnJedis(client);
		}
	}

	/**
	 * Description:关闭jedis
	 */
	public void returnJedis(Jedis jedis) {
		if (jedis != null) {
			jedis.close();
		}
	}
}